import Api from "@/api"

const axios = require('axios').create({
  baseURL: process.env.API_ROOT
})
axios.defaults.timeout = 30000

let _token
let _namespace = 'DEFAULT_NS'
let _loginTimeout

let $vue

let interceptors = {
  requestSuccess(config) {
    // 设置Header
    config.headers.common = config.headers.common || {}
    config.headers.common['unistar_api_token'] = _token
    // 开启loading
    $vue.$util.showLoading()
    //
    return config
  },
  requestFail(e) {
    $vue.$util.hideLoading()
    return Promise.resolve({
      retCode: 0,
      retMsg: 'server.requestfail'
    })
  },
  responseSuccess(resp) {
    $vue.$util.hideLoading()
    let data = resp.data
    if (data && data.retCode === -1) {
      if (_loginTimeout) _loginTimeout()
      return Promise.resolve({ retCode: 0 })
    }
    return Promise.resolve(data || { retCode: 0 })
  },
  responseFail(e) {
    $vue.$util.hideLoading()
    return Promise.resolve({
      retCode: 0,
      retMsg: 'server.responsefail'
    })
  },
}

function XcHttp(_vue) {
  $vue = _vue
  axios.interceptors.request.use(interceptors.requestSuccess, interceptors.requestFail)
  axios.interceptors.response.use(interceptors.responseSuccess, interceptors.responseFail)
}

XcHttp.prototype.setToken = function (token) {
  if (_token === token) return
  _token = token
}

XcHttp.prototype.setLoginTimeout = function (loginTimeout) {
  _loginTimeout = loginTimeout
}

/**
 * @param namespace 命名空间
 */
XcHttp.prototype.changeNamespace = function (namespace) {
  if (_namespace === namespace) return
  _namespace = namespace
}

XcHttp.prototype.dispatch = function (name, params) {
  let data = params || {}
  data.namespace = _namespace
  return axios.request({
    url: Api[name].path,
    method: Api[name].method,
    data: data
  })
}

export default XcHttp
